package sort;

/**
 * @author way
 * @create 2025-03-17 21:09
 */
public class InsertSort {
    /**
     * 插入排序:已排序|待排序，每次将待排序元素插入到前方已排序数组中
     *
     * @param a
     */
    public void insertSort(int[] a) {
        int len = a.length;
        for (int i = 1; i < len; ++i) {
            for (int j = i; j > 0 && a[j - 1] > a[j]; j--) {
                swap(a, j - 1, j);
            }
        }
    }

    public void insertSort1(int[] a, int len) {
        for (int i = 1; i < len; ++i) {
            int cur = i;
            int last = a[cur];
            while (cur > 0 && a[cur - 1] > last) {
                a[cur] = a[cur - 1];
                cur--;
            }
            a[cur] = last;
        }
    }

    public void swap(int[] a, int i, int j) {
        int temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{5, 4, 3, 8, 2, 7, 9, 1};
        InsertSort sort = new InsertSort();
        sort.insertSort(arr);
        for (int i : arr) {
            System.out.println(i);
        }
    }
}
